<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #canvas {
            border: 1px solid #ff0000;
        }
    </style>
</head>
<body>

    <canvas id="canvas" width="600" height="400"></canvas>

    <script>
        // 1、获取元素
        var myCanvas = document.querySelector("#canvas");
        var ctx = myCanvas.getContext("2d");
     
        // 1、绘制网格
        // 2、网格的大小
        var girdSize = 20;
        // 3、画多少条X轴方向的线(横线) 与高度有关
        // var canvasHeight = myCanvas.height;//通过dom操作
        var canvasWidth = ctx.canvas.width;
        var canvasHeight = ctx.canvas.height;//通过canvas上下文获取画布宽高
        var xLineTotal = Math.floor(canvasHeight / girdSize);
        for (let i=0;i<=xLineTotal;i++) {
            ctx.beginPath();
            ctx.moveTo(0, i * girdSize - 0.5);
            ctx.lineTo(canvasWidth, i * girdSize - 0.5);
            ctx.strokeStyle = "#AAA";
            ctx.stroke();
        }

        // 4、画多少条Y轴方向的线(竖线)
        var yLineTotal = Math.floor(canvasWidth / girdSize);
        for (let i = 0; i <= yLineTotal; i++) {
            ctx.beginPath();
            ctx.moveTo(i * girdSize + 0.5,0);
            ctx.lineTo(i * girdSize + 0.5,canvasHeight);
            ctx.strokeStyle = "#AAA";
            ctx.stroke();
        }

    </script>
</body>
</html>